Guava简介

Google Guava很优秀,大有取代Apache Commons之势。闲话少叙,直接上Guava的终极目标,用原汁原味的英文来说就是“Our goal is for you to write less code and for the code you do write to be simpler, cleaner, and more readable”,Guava中主要包括Basic Utilities,Collections,Caches,Functional Idioms,Concurrency,Strings,Primitives Support,Ranges,I/O等等,API参考文档点我,Guava在Github上仓库地址点我

Guava使用示例

Preconditions

可以用在方法的开始或者是构造函数的开始,对于不合法的校验可以快速报错

  1. package cn.codepub.guava.demo;
  2. import static com.google.common.base.Preconditions.checkArgument;
  3. import static com.google.common.base.Preconditions.checkNotNull;
  4. /**
  5. * <p>
  6. * Created with IntelliJ IDEA. 2015/11/28 20:12
  7. * </p>
  8. * <p>
  9. * ClassName:PreconditionsDemo
  10. * </p>
  11. * <p>
  12. * Description:TODO
  13. * </P>
  14. *
  15. * @author Wang Xu
  16. * @version V1.0.0
  17. * @since V1.0.0
  18. */
  19. public class PreconditionsDemo {
  20. public static void main(String[] args) {
  21. new Car(null);//Exception in thread "main" java.lang.NullPointerException
  22. //Exception in thread "main" java.lang.IllegalArgumentException: speed (0.0) must be positive
  23. new Car("Audi").drive(0);
  24. }
  25. }
  26. class Car {
  27. private String name;
  28. public Car(String name) {
  29. this.name = checkNotNull(name);//NPE Null Pointer Exception
  30. }
  31. public void drive(double speed) {
  32. checkArgument(speed > 0.0, "speed (%s) must be positive", speed);
  33. }
  34. }
MoreObjects.toStringHelper()

让你可以更优雅的覆写Object.toString()方法

  1. package cn.codepub.guava.demo;
  2. import com.google.common.base.MoreObjects;
  3. /**
  4. * <p>
  5. * Created with IntelliJ IDEA. 2015/11/28 20:26
  6. * </p>
  7. * <p>
  8. * ClassName:MoreObjectsDemo
  9. * </p>
  10. * <p>
  11. * Description:TODO
  12. * </P>
  13. *
  14. * @author Wang Xu
  15. * @version V1.0.0
  16. * @since V1.0.0
  17. */
  18. public class MoreObjectsDemo {
  19. private String name;
  20. private String userId;
  21. private String petName;
  22. private String sex;
  23. @Override
  24. public String toString() {
  25. //prints:MoreObjectsDemo{name=testName, userId=NO1, petName=PIG}
  26. return MoreObjects.toStringHelper(this).add("name", "testName").add("userId", "NO1").add("petName", "PIG").omitNullValues().toString();
  27. //prints:MoreObjectsDemo{name=testName, userId=NO1, petName=PIG}
  28. //return MoreObjects.toStringHelper(this).add("name", "testName").add("userId", "NO1").add("petName", "PIG").toString();
  29. }
  30. public static void main(String[] args) {
  31. System.out.println(new MoreObjectsDemo());
  32. }
  33. }
用Stopwatch代替System.nanoTime()

简单点说就是Stopwatch使用纳秒计时,使用该类度量时间比使用System.nanoTime()好,好处在哪呢?基于性能和测试来说,它可以作为另一种替代时间源;根据System.nanoTime()的说明,返回的值没有绝对意义,只能解释为相对于另一个返回的时间戳。Stopwatch是一个更有效的抽象,因为它只公开这些相对的值,而不是绝对值。可以通过其提供的startstop方法得到。

  1. package cn.codepub.guava.demo;
  2. import com.google.common.base.Stopwatch;
  3. import java.util.concurrent.TimeUnit;
  4. /**
  5. * <p>
  6. * Created with IntelliJ IDEA. 2015/11/28 20:53
  7. * </p>
  8. * <p>
  9. * ClassName:StopWatchDemo
  10. * </p>
  11. * <p>
  12. * Description:TODO
  13. * </P>
  14. *
  15. * @author Wang Xu
  16. * @version V1.0.0
  17. * @since V1.0.0
  18. */
  19. public class StopWatchDemo {
  20. public static void main(String[] args) {
  21. //The Construct Stopwatch is default access permissions
  22. Stopwatch stopwatch = Stopwatch.createUnstarted();
  23. //start
  24. stopwatch.start();
  25. System.out.println("You can do something!");
  26. try {
  27. Thread.sleep(1000);
  28. } catch (InterruptedException e) {
  29. e.printStackTrace();
  30. }
  31. stopwatch.stop();
  32. long nanos = stopwatch.elapsed(TimeUnit.NANOSECONDS);
  33. System.out.println(nanos);//1000076976
  34. }
  35. }
CharMatcher
  1. package cn.codepub.guava.demo;
  2. import com.google.common.base.CharMatcher;
  3. /**
  4. * <p>
  5. * Created with IntelliJ IDEA. 2015/11/28 21:31
  6. * </p>
  7. * <p>
  8. * ClassName:CharMatcherDemo
  9. * </p>
  10. * <p>
  11. * Description:TODO
  12. * </P>
  13. *
  14. * @author Wang Xu
  15. * @version V1.0.0
  16. * @since V1.0.0
  17. */
  18. public class CharMatcherDemo {
  19. private static final CharMatcher ID_MATCHER = CharMatcher.DIGIT.or(CharMatcher.is('-'));
  20. public static void main(String[] args) {
  21. String userID = "123454-333";
  22. String s = ID_MATCHER.retainFrom(userID);
  23. System.out.println(s);//123454-333
  24. s = ID_MATCHER.retainFrom("1 test 11-222");
  25. System.out.println(s);//111-222
  26. }
  27. }
String Joining
  1. package cn.codepub.guava.demo;
  2. import com.google.common.base.Joiner;
  3. /**
  4. * <p>
  5. * Created with IntelliJ IDEA. 2015/11/28 21:43
  6. * </p>
  7. * <p>
  8. * ClassName:StringJoiningDemo
  9. * </p>
  10. * <p>
  11. * Description:TODO
  12. * </P>
  13. *
  14. * @author Wang Xu
  15. * @version V1.0.0
  16. * @since V1.0.0
  17. */
  18. public class StringJoiningDemo {
  19. private static final Joiner JOINER = Joiner.on(",").skipNulls();
  20. //set replace string
  21. private static final Joiner JOINER_USE_FOR_NULL = Joiner.on(",").useForNull("replace");
  22. public static void main(String[] args) {
  23. String join = JOINER.join("Kurt", "Kevin", null, "Chris");
  24. System.out.println(join);//Kurt, Kevin, Chris
  25. join = JOINER_USE_FOR_NULL.join("Kurt", "Kevin", null, "Chris");
  26. System.out.println(join);
  27. }
  28. }
String Splitting

使用指定的分隔符对字符串进行拆分,默认对空白符不做任何处理,并且不会静默的丢弃末尾分隔符,如果需要处理的话要显式调用trimResults()omitEmptyStrings()

  1. package cn.codepub.guava.demo;
  2. import com.google.common.base.Splitter;
  3. /**
  4. * <p>
  5. * Created with IntelliJ IDEA. 2015/11/28 21:57
  6. * </p>
  7. * <p>
  8. * ClassName:SplitterDemo
  9. * </p>
  10. * <p>
  11. * Description:TODO
  12. * </P>
  13. *
  14. * @author Wang Xu
  15. * @version V1.0.0
  16. * @since V1.0.0
  17. */
  18. public class SplitterDemo {
  19. public static void main(String[] args) {
  20. Iterable<String> split = Splitter.on(',').trimResults().omitEmptyStrings()
  21. .split("foo, ,bar,quux,blue,");
  22. for (String s : split) {
  23. System.out.print(s + "---");//foo---bar---quux---blue---
  24. }
  25. System.out.println();
  26. String[] split1 = "foo, ,bar,quux,blue,".split(",");
  27. for (String s : split1) {
  28. System.out.print(s + "---");//foo--- ---bar---quux---blue---
  29. }
  30. }
  31. }
Optional
  1. package cn.codepub.guava.demo;
  2. import java.util.Optional;
  3. /**
  4. * <p>
  5. * Created with IntelliJ IDEA. 2015/11/28 22:24
  6. * </p>
  7. * <p>
  8. * ClassName:OptionalDemo
  9. * </p>
  10. * <p>
  11. * Description:TODO
  12. * </P>
  13. *
  14. * @author Wang Xu
  15. * @version V1.0.0
  16. * @since V1.0.0
  17. */
  18. public class OptionalDemo {
  19. public static void main(String[] args) {
  20. //Creating an Optional<T>
  21. //Optional.of(notNull);
  22. //Optional.empty();
  23. //Optional.ofNullable(maybeNull);
  24. String test = "test";
  25. // if test == null will throws NPE
  26. Optional<String> s = Optional.of(test);
  27. System.out.println(s.get());//test
  28. Optional<Object> empty = Optional.empty();
  29. System.out.println(empty);//Optional.empty
  30. Optional<Object> o = Optional.ofNullable(null);
  31. System.out.println(o);//Optional.empty
  32. }
  33. }
Hashing
  1. package cn.codepub.guava.demo;
  2. import com.google.common.base.Charsets;
  3. import com.google.common.hash.HashCode;
  4. import com.google.common.hash.Hashing;
  5. /**
  6. * <p>
  7. * Created with IntelliJ IDEA. 2015/11/29 16:24
  8. * </p>
  9. * <p>
  10. * ClassName:HashingDemo
  11. * </p>
  12. * <p>
  13. * Description:TODO
  14. * </P>
  15. *
  16. * @author Wang Xu
  17. * @version V1.0.0
  18. * @since V1.0.0
  19. */
  20. public class HashingDemo {
  21. public static void main(String[] args) {
  22. byte sex = 1;
  23. Person person = new Person(100, "eric", "wang", 1L, sex);
  24. System.out.println(person.hashCode());//1935260882
  25. }
  26. }
  27. class Person {
  28. private int age;
  29. private String firstName;
  30. private String lastName;
  31. private long id;
  32. private byte sex;
  33. public Person(int age, String firstName, String lastName, long id, byte sex) {
  34. this.age = age;
  35. this.firstName = firstName;
  36. this.lastName = lastName;
  37. this.id = id;
  38. this.sex = sex;
  39. }
  40. public int getAge() {
  41. return this.age;
  42. }
  43. public String getFirstName() {
  44. return this.firstName;
  45. }
  46. public String getLastName() {
  47. return this.lastName;
  48. }
  49. public long getId() {
  50. return this.id;
  51. }
  52. public byte getSex() {
  53. return this.sex;
  54. }
  55. @Override
  56. public int hashCode() {
  57. HashCode hashCode = Hashing.murmur3_128().newHasher().putInt(this.getAge()).putLong(this.getId())
  58. .putString(this.getFirstName(), Charsets.UTF_8).putString(this.getLastName(), Charsets.UTF_8)
  59. .putByte(this.getSex()).hash();
  60. return hashCode.hashCode();
  61. }
  62. }
Caching
  1. package cn.codepub.guava.demo;
  2. import com.google.common.cache.*;
  3. import com.sun.corba.se.impl.orbutil.graph.Graph;
  4. import java.security.Key;
  5. import java.util.concurrent.TimeUnit;
  6. /**
  7. * <p>
  8. * Created with IntelliJ IDEA. 2015/11/29 16:54
  9. * </p>
  10. * <p>
  11. * ClassName:CachingDemo
  12. * </p>
  13. * <p>
  14. * Description:TODO
  15. * </P>
  16. *
  17. * @author Wang Xu
  18. * @version V1.0.0
  19. * @since V1.0.0
  20. */
  21. public class CachingDemo {
  22. LoadingCache<Key, Graph> cache = CacheBuilder.newBuilder().maximumSize(10000)
  23. .expireAfterWrite(10, TimeUnit.MINUTES).removalListener(new RemovalListener<Object, Object>() {
  24. @Override
  25. public void onRemoval(RemovalNotification<Object, Object> removalNotification) {
  26. //implements your listener
  27. }
  28. }).build(new CacheLoader<Key, Graph>() {
  29. @Override
  30. public Graph load(Key key) throws Exception {
  31. return null;
  32. }
  33. });
  34. }
链式调用

Guava中提供了大量方法,让我们可以使用链式调用的方式从而减少代码量。简单来说方法链一般适合对一个对象进行连续操作(集中在一句代码)。一定程度上可以减少代码量,缺点是它占用了函数的返回值。如果不需要使用到函数返回值的话,建议大家在封装自己的代码库的时候可以使用这种方式,提供一个简单的demo如下:

  1. package cn.codepub.guava.demo;
  2. /**
  3. * <p>
  4. * Created with IntelliJ IDEA. 2015/11/29 16:00
  5. * </p>
  6. * <p>
  7. * ClassName:ChainEncapsulationDemo
  8. * </p>
  9. * <p>
  10. * Description:TODO
  11. * </P>
  12. *
  13. * @author Wang Xu
  14. * @version V1.0.0
  15. * @since V1.0.0
  16. */
  17. public class ChainEncapsulationDemo {
  18. private String message = "";
  19. public String getMessage() {
  20. return message;
  21. }
  22. public void setMessage(String message) {
  23. this.message = message;
  24. }
  25. public static void main(String[] args) {
  26. ChainEncapsulationDemo chainEncapsulationDemo = new ChainEncapsulationDemo();
  27. chainEncapsulationDemo = chainEncapsulationDemo.method1().method2().method3();
  28. System.out.println(chainEncapsulationDemo.getMessage());
  29. }
  30. public ChainEncapsulationDemo method1() {
  31. this.setMessage(this.getMessage() + "add method1 ...\n");
  32. return this;
  33. }
  34. public ChainEncapsulationDemo method2() {
  35. this.setMessage(this.getMessage() + "add method2 ...\n");
  36. return this;
  37. }
  38. public ChainEncapsulationDemo method3() {
  39. this.setMessage(this.getMessage() + "add method3 ...");
  40. return this;
  41. }
  42. }
Apache VS. Guava

关于使用Apache Commons还是Guava的讨论看这里